package com.chinaunicom.auth.config;

import com.chinaunicom.auth.service.impl.UserDetailServiceImpl;
import com.chinaunicom.auth.sms.SmsCodeAuthenticationProvider;
import com.chinaunicom.auth.sms.SmsCodeAuthenticationSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/3/6 23:26
 * Description:
 */

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailServiceImpl userDetailService;

    @Resource
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private SmsCodeAuthenticationProvider smsAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭请求伪造
        http.csrf().disable();
        http.formLogin();
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .apply(smsCodeAuthenticationSecurityConfig);
    }


    /**
     * 在内存中配置信息
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
////        auth.inMemoryAuthentication()
////                .withUser("admin")
////                .password(passwordEncoder.encode("root"))
////                .authorities("sys:admin");
//
        auth.userDetailsService(userDetailService)
                .and()
                .authenticationProvider(smsAuthenticationProvider());
    }


    /**
     * 使用密码授权模式不需要登录，内部需要一个认证管理器
     *
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 这一步的配置是必不可少的，否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
     *
     * @return 认证管理对象
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 认证
     *
     * @return
     */
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        //对默认的UserDetailsService进行覆盖
        authenticationProvider.setUserDetailsService(userDetailService);
        authenticationProvider.setPasswordEncoder(new PasswordEncoder() {

            // 对密码未加密
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            // 判断密码是否正确, rawPassword 用户输入的密码,  encodedPassword 数据库DB的密码,当 userDetailService的loadUserByUsername方法执行完后执行
            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return rawPassword.toString().equalsIgnoreCase(encodedPassword);
            }
        });
        return authenticationProvider;
    }


//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        // TODO Auto-generated method stub
//        auth.authenticationProvider(authenticationProvider());
//        auth.authenticationProvider(smsAuthenticationProvider());
//    }

    @Bean
    public SmsCodeAuthenticationProvider smsAuthenticationProvider() {
        return new SmsCodeAuthenticationProvider(userDetailService);
    }

}
